package com.lin.missyou.repository;

import com.lin.missyou.core.money.IMoneyDiscount;
import com.lin.missyou.models.UserCoupon;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import java.util.Optional;


@Repository
public interface UserCouponRepository extends JpaRepository<UserCoupon, Long> {
    Optional<UserCoupon> findFirstByUserIdAndCouponIdAndStatus(Long userId, Long couponId, Integer status);

    Optional<UserCoupon> findFirstByUserIdAndCouponId(Long userId, Long couponId);


    @Modifying
    @Query("update UserCoupon uc " +
            "set uc.orderId=:oid," +
            "uc.status = 2 " +
            "where uc.userId = :uid " +
            "and uc.couponId = :couponId " +
            "and uc.status=1 " +
            "and uc.orderId is null")
    int writeoff(Long couponId, Long oid, Long uid);

    @Modifying
    @Query("update UserCoupon uc set uc.status =1,uc.orderId=null where uc.userId= :uid and uc.couponId = :couponId and uc.orderId != null and uc.status=2")
    int returnBack(Long couponId,Long uid);
}
